import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { useReactive } from 'ahooks';
import SearchScreen from '../../../component/SearchScreen';
import { useSelector } from 'react-redux';
import { RootState } from '../../../redux/store.ts';
import { CommonStyle } from '../../../common/commonStyle.ts';
import AntDesign from 'react-native-vector-icons/AntDesign';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { Actionsheet, useDisclose } from 'native-base';
import SelectBeeper from '../../../component/SelectBeeper.tsx';
import OrderCard from '../../../component/OrderCard.tsx';
import CustomFlatList from '../../../component/CustomFlatList.tsx';
import HomeRequest from '../../../request/homeRequest.ts';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import to from '../../../utils/to.ts';

interface IOrderScreenProps {
  navigation: NavigationProp<any, 'order'>;
  route: RouteProp<{ order: any }, 'order'>;
}

interface IData {
  tabActive: string;
  beeperModalShow: boolean;
  beeperList: IGetCallListRes[];
  pages: {
    pageNo: number;
    totalPage: number;
  };
  orderList: IOrderList[];
  isLoading: boolean;
  refreshing: boolean;
  selectList: {
    id: number;
    name: string;
  }[];
}

interface IScreen {
  orderState: number | string;
  date: number | string;
  beginDate: string;
  endDate: string;
  groupValue: string;
}

const OrderScreen: React.FC<IOrderScreenProps> = ({ navigation, route }) => {
  const data = useReactive<IData>({
    tabActive: 'N',
    beeperModalShow: false,
    beeperList: [],
    pages: {
      pageNo: 1,
      totalPage: 1,
    },
    orderList: [],
    isLoading: false,
    refreshing: false,
    selectList: [],
  });

  const screenData = useReactive<IScreen>({
    orderState: 0,
    date: 0,
    beginDate: '',
    endDate: '',
    groupValue: '',
  });

  const { isOpen, onOpen, onClose } = useDisclose();

  const [beeperId, setBeeperId] = useState(useSelector((state: RootState) => state.beeperId));

  const btnInformation = useSelector((state: RootState) => state.btnInformation); //按钮里面的数据

  const screenConfirm = (item: IScreen) => {
    Object.assign(screenData, item);
    customListRefresh(1);
  };

  const screenRepeat = (item: IScreen) => {
    customListRefresh(1);
  };

  const getBeeperData = (id: number, item: IGetCallListRes) => {
    const filterItem = [
      { name: '周边服务', id: -1 },
      {
        name: item.name,
        id: item.id,
      }
    ];
    data.selectList = filterItem;
    setBeeperId(id);
  };

  const getBeeperList = async () => {
    const [err, callList] = await to(HomeRequest.GetCallerList({ type: 2 }));
    if (err) {
      return;
    }
    const item = callList.data.filter((item) => item.id === beeperId)[0];
    const filterItem = [
      { name: '周边服务', id: -1 },
      {
        name: item.name,
        id: item.id,
      }
    ];
    data.selectList = filterItem;
  };

  const getOrderList = () => {
    Loading.show('加载中');
    let { pageNo, totalPage } = data.pages;
    if (pageNo <= totalPage) {
      data.isLoading = true;
      const params = {
        pageNo,
        pageSize: 10,
        beeperId,
        ...screenData,
        date:screenData.date===0?'':screenData.date,
        orderState:screenData.orderState===0?'':screenData.orderState,
      };
      console.log(params);
      HomeRequest.GetOrderList(params)
        .then((res) => {
          Loading.hide();
          data.orderList = [...data.orderList, ...res.data.list];
          data.pages.totalPage = res.data.totalPage;
          data.pages.pageNo += 1;
          data.isLoading = false;
          data.refreshing = false;
        })
        .catch((err) => {
          data.isLoading = false;
          data.refreshing = false;
          Loading.hide();
        });
    } else {
      Loading.hide();
    }
  };

  const customListRefresh = (type?: number) => {
    if (!type) {
      data.refreshing = true;
    }
    data.orderList = [];
    data.pages.pageNo = 1;
    data.pages.totalPage = 1;
    getOrderList();
  };

  useEffect(() => {
    getOrderList();
    getBeeperList();
  }, []);
  
  useEffect(() => {
    customListRefresh(1);
  }, [beeperId]);

  return (
    <View>
      <SearchScreen onConfirm={screenConfirm} onRepeat={screenRepeat}></SearchScreen>
      <View style={styles.actionBar}>
        <View style={styles.actionLeft}>
          <TouchableOpacity
            style={styles.actionBtn}
            onPress={() => {
              onOpen();
            }}
          >
            <Text style={{ color: '#fff' }}>{data.selectList?.filter((item) => beeperId === item.id)[0]?.name || ''}</Text>
            <AntDesign name="down" color={'#fff'} size={16} style={{ marginTop: 4, marginLeft: 4 }}></AntDesign>
          </TouchableOpacity>
        </View>
        <View style={styles.actionRight}>
          <TouchableOpacity style={styles.iconBox}>
            <MaterialIcons name="file-download" size={24} color={CommonStyle.mainColor}></MaterialIcons>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.iconBox}
            onPress={() => {
              data.beeperModalShow = !data.beeperModalShow;
            }}
          >
            <MaterialIcons name={'manage-search'} size={24} color={'#ea622c'} />
          </TouchableOpacity>
        </View>
      </View>
      <View style={styles.orderList}>
        <CustomFlatList data={data.orderList} renderItem={({ item, index }) => <OrderCard orderInfo={item} index={index}/>} refreshing={data.refreshing} isLoading={data.isLoading} onEndReached={getOrderList} onRefresh={customListRefresh}></CustomFlatList>
      </View>
      <Actionsheet isOpen={isOpen} onClose={onClose}>
        <Actionsheet.Content>
          {data.selectList.map((item, index) => (
            <Actionsheet.Item
              key={index}
              onPress={() => {
                setBeeperId(item.id);
                onClose();
              }}
            >
              {item.name}
            </Actionsheet.Item>
          ))}
        </Actionsheet.Content>
      </Actionsheet>
      <SelectBeeper
        onSelected={getBeeperData}
        onModalShow={(e) => {
          data.beeperModalShow = e;
        }}
        beeperId={beeperId}
        isModalVisible={data.beeperModalShow}
      ></SelectBeeper>
    </View>
  );
};
const styles = StyleSheet.create({
  content: {
    flex: 1,
    paddingHorizontal: 16,
    paddingVertical: 16,
  },
  actionBar: {
    flexDirection: 'row',
    height: 50,
    paddingHorizontal: 10,
    width: '100%',
    alignItems: 'center',
  },
  actionLeft: {
    flex: 0,
  },
  actionBtn: {
    backgroundColor: CommonStyle.mainColor,
    width: 'auto',
    height: 34,
    paddingHorizontal: 10,
    justifyContent: 'center',
    borderRadius: 8,
    flexDirection: 'row',
    alignItems: 'center',
  },
  actionRight: {
    flex: 1,
    justifyContent: 'flex-end',
    flexDirection: 'row',
  },
  iconBox: { backgroundColor: '#fff', flexDirection: 'row', alignItems: 'center', justifyContent: 'center', width: 33, height: 33, borderRadius: 50, marginLeft: 10 },
  orderList: {
    paddingHorizontal: 10,
    marginBottom: 200,
  },
});

export default OrderScreen;
